package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // TODO: [222024321072010/黄天灿] 根据请求的URL获取Handler
        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            // TODO: [222024321072010/黄天灿] 如果连DefaultHandler都没有，返回500 Internal Server Error
            String body = "<html><head><title>500</title></head>"
                    + "<body><h1>500 Internal Server Error</h1>"
                    + "<p>No handler found and no default handler.</p></body></html>";
            int len = body.getBytes().length;
            PrintWriter pw = new PrintWriter(response);
            pw.printf("HTTP/1.1 500 Internal Server Error\r\n");
            pw.printf("Content-Type: text/html;charset=utf-8\r\n");
            pw.printf("Content-Length: %d\r\n", len);
            pw.printf("Connection: close\r\n");
            pw.printf("\r\n");
            pw.print(body);
            pw.flush();
        }
    }
}